package com.hy.logtrace.util;

import com.hy.logtrace.config.LogTraceProperties;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @Description: TraceIdContext
 * 用于日志记录TraceId的上下文
 */
@Component
public class TraceIdContext {
    private static final ThreadLocal<String> TRACE_ID_CONTEXT = new ThreadLocal<>();

    private static String TRACE_KEY = "";

    public TraceIdContext(LogTraceProperties properties) {
        TRACE_KEY = properties.getTraceKey();
    }

    public static String getTraceKey() {
        return TRACE_KEY;
    }


    public static String generateTraceId() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static void setTraceId(String traceId) {
        TRACE_ID_CONTEXT.set(traceId);
    }

    public static String getTraceId() {
        return TRACE_ID_CONTEXT.get();
    }

    public static void clear() {
        TRACE_ID_CONTEXT.remove();
    }
}